package chapter5.homework.heima.Q4updateFilesAndPreventDuplicateNames;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Project ：learn_java
 * @File ：Server.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/16 17:08
 * @Description ：和题3功能差不多，但如果选择的文件与已经上传的文件出现重名时，将取消上传文件
 */

public class Server {
    public static void main(String[] args) {
        int samePort = 10086;

        ArrayList<String> updatedFiles = new ArrayList<>();

        try (ServerSocket ss = new ServerSocket(samePort)) {
            System.out.println("服务器已启动，等待客户端连接...");
            try (Socket socket = ss.accept()) {
                System.out.println("客户端已连接");

                String name = UUID.randomUUID().toString().replace("-", "");
                String saveDir = "G:\\codes\\learn_java\\src\\chapter5\\ServerDir\\aoa" + name + ".webp";

                try (BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveDir))) {

                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, len);
                    }
                    bos.flush(); // 确保所有数据写入文件
                }

                // 回写反馈
                try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
                    bw.write("上传成功");
                    bw.newLine();
                    bw.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
